package login;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.mobile.auth.gatewayauth.AuthUIConfig;
import com.mobile.auth.gatewayauth.PhoneNumberAuthHelper;
import com.mobile.auth.gatewayauth.ResultCode;
import com.mobile.auth.gatewayauth.TokenResultListener;
import com.mobile.auth.gatewayauth.model.TokenRet;

import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;

public class LogInPlugin implements MethodChannel.MethodCallHandler , FlutterPlugin {
    public static final String CHANNEL = "com.ahj/LoginPlugin";
    static MethodChannel channe;
    private Activity activity;
    public static  MethodChannel.Result result;
    public LogInPlugin(Activity activity) {
        this.activity = activity;
    }


    private PhoneNumberAuthHelper mPhoneNumberAuthHelper;
    private TokenResultListener mTokenResultListener;
    private ProgressDialog mProgressDialog;
    public static final String AUTH_SECRET = "A1k1xuainJFM/LLfjsMDLKiLmg7Imd/ll5lAAlQgGI7k4M91mmUpPH7+UQXz+VzvciRTrIkRjOerCPi1kugZwCRTURYNNp/r/B7E+v5YcfJ0DESfCvp0T9caslANf/cFushC+2wc1w5FUw/4VU2VO81BwbEo7YO5ko+hj4epVOaD8ibA4UznZOiWsIt3WD8pi4bYYAtadic3Izj8gWcm5WPayPUN7OtEJ9szcTDapBSG6W2QhqNQdeAzyj6+L03wm8VkkScBcf0t5oAkQv2Te0wwWE1vsvO6L4CeKNjALeQZ7+b3Nvq7Ww==";


    public static void registerWith(FlutterEngine flutterEngine, Activity activity12) {
        channe = new MethodChannel(flutterEngine.getDartExecutor(), CHANNEL);
        LogInPlugin plugin = new LogInPlugin(activity12);
        channe.setMethodCallHandler(plugin);
    }


    @Override
    public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
        try {
            if (methodCall.method.equals("yijiandenglu")) {
                this.result=result;
//                Log.e("sssss","videoType::zhuJiangPerson"+videoType);
//                Intent intent=new Intent(activity, OneKeyLoginActivity.class);
//
//                activity.startActivity(intent);


                sdkInit(AUTH_SECRET);
                oneKeyLogin();

            }

        } catch (Exception e) {
            e.printStackTrace();
            result.success("");
        }
    }

    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) {

    }

    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {

    }


    public void sdkInit(String secretInfo) {
        Log.e("TAG", "唤起授权页成功：" + "31231");
        mTokenResultListener = new TokenResultListener() {
            @Override
            public void onTokenSuccess(String s) {
                hideLoadingDialog();
                TokenRet tokenRet = null;
                try {
                    tokenRet = TokenRet.fromJson(s);
                    if (ResultCode.CODE_START_AUTHPAGE_SUCCESS.equals(tokenRet.getCode())) {
                        Log.e("TAG", "唤起授权页成功：" + s);
                    }

                    if (ResultCode.CODE_SUCCESS.equals(tokenRet.getCode())) {
                        Log.e("TAG", "获取token成功：" + s);
                        LogInPlugin.result.success(tokenRet.getToken());
                        mPhoneNumberAuthHelper.quitLoginPage();
                        getResultWithToken(tokenRet.getToken());

                        mPhoneNumberAuthHelper.setAuthListener(null);
                    }
                } catch (Exception e) {
                    Log.e("TAG",  e.toString());
                    e.printStackTrace();
                }
            }

            @Override
            public void onTokenFailed(String s) {
//                result.success("1");
                Log.e("312", "获取token失败：" + s);
                hideLoadingDialog();
                TokenRet tokenRet = null;
                try {
                    tokenRet = TokenRet.fromJson(s);
                    if (ResultCode.CODE_ERROR_USER_CANCEL.equals(tokenRet.getCode())) {
                        //模拟的是必须登录 否则直接退出app的场景
                        LogInPlugin.result.success("-100");
                    } else {

                        String   message="一键登录失败切换到其他登录方式";
                        if (tokenRet.getCode().equals("600005")||tokenRet.getCode().equals("600011")){//请切换到其他方式登录
                            LogInPlugin.result.success("-100");
                        }else if (tokenRet.getCode().equals("600008")){//请先开启移动数据网络
                            LogInPlugin.result.success("-100");
                            message="请先开启移动数据网络后重试";
                        }else if (tokenRet.getCode().equals("600009")||tokenRet.getCode().equals("600007")){//未检测到SIM卡
                            LogInPlugin.result.success("-100");
                            message="请先检查SIM卡后重试";
                        } else  {
                            LogInPlugin.result.success("-100");
                        }

                        Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
                        mPhoneNumberAuthHelper.quitLoginPage();
                    }
                } catch (Exception e) {
                    LogInPlugin.result.success("-100");
                    e.printStackTrace();
                }
                mPhoneNumberAuthHelper.setAuthListener(null);
            }
        };
        mPhoneNumberAuthHelper = PhoneNumberAuthHelper.getInstance(activity, mTokenResultListener);
        mPhoneNumberAuthHelper.getReporter().setLoggerEnable(true);
        mPhoneNumberAuthHelper.setAuthSDKInfo(secretInfo);

        mPhoneNumberAuthHelper.setAuthUIConfig(
                new AuthUIConfig.Builder()
                        .setLogBtnText("⼀键登录")
                        .setLogBtnTextColor(Color.WHITE).setLogoHidden(false)
                        .setNavColor(0xff379DF2)
                        .setNavText("免密登录")
                        .setNavTextColor(Color.WHITE)
                        .setNumberColor(Color.WHITE)
                        .setStatusBarColor(0xff379DF2)
                        .setNumberSize(28)
                        .setNumberColor(0xff000000).create());
    }



    /**
     * 进入app就需要登录的场景使用
     */
    private void oneKeyLogin() {
        mPhoneNumberAuthHelper = PhoneNumberAuthHelper.getInstance(activity, mTokenResultListener);
        mPhoneNumberAuthHelper.checkEnvAvailable();

        getLoginToken(5000);
    }

    /**
     * 拉起授权页
     * @param timeout 超时时间
     */
    public void getLoginToken(int timeout) {
        mPhoneNumberAuthHelper.getLoginToken(activity, timeout);
        showLoadingDialog("正在唤起授权页");
    }


    public void getResultWithToken(final String token) {
//        LogInPlugin.result.success(token);

//        Toast.makeText(activity, ""+token, Toast.LENGTH_SHORT).show();
    }






    public void showLoadingDialog(String hint) {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(activity);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        }
        mProgressDialog.setMessage(hint);
        mProgressDialog.setCancelable(true);
        mProgressDialog.show();
    }

    public void hideLoadingDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }

}
